var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
    upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
}
function fy_dialog_close() {
//	window.parent.$(".mask").remove();
//	window.parent.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
    window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
}

function getUpFields(name) {
    return upWindow.$("[validate*='name:\"" + name + "\"']");
}
function getUpFieldsByFieldval(name) {
    return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}
function getUpAccountFieldValue(name) {
    var field = getUpFields(name).eq(0);
    return {
        displayValue: field.is("span") ? field.text() : field.val(),
        value: eval("(" + field.parent("span").attr("fieldVal") + ")").value
    };
}

function addOrDelRepeat(name, newLength) {
    var fields = getUpFieldsByFieldval(name);
    var oldLength = fields.length;
    var tbody = getUpFieldsByFieldval(name).eq(0).parent();
    while (!tbody.is("tbody")) {
        tbody = tbody.parent();
    }
    for (var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
        if (newLength > oldLength) {
            upWindow.fy_addEmpty(tbody.children().last());
        } else {
            upWindow.fy_delCurrentRepeat(tbody.children().last());
        }
    }
}

function getUpFieldValue(field) {
    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var browseTag = field.hasClass(browseClass);
    var addTag = field.hasClass(addClass);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }
    var obj = new Object();
    obj.displayName = fieldVal.displayName;
    obj.name = fieldVal.name;
    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "checkbox":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "radio":
            if (editTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            }
            break;
        case "select":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + " option:selected")
                        .attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).attr("val4cal");
            }
            break;
        case "date":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
                if (obj.value != "") {
                    obj.value = obj.value + " 00:00";
                }
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "datetime":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "flowdealoption":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "lable":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relationform":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relation":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "project":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + "_txt").val();
                obj.id = field.find("#" + fieldVal.name).val().split('|')[1];
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).text();
            }
            break;
        case "attachment":
        case "image":
        case "document":
            if (editTag || browseTag) {
                var attNames = "";
                var tempField = field.find("#" + fieldVal.name);
                var tempFileId = "";
                if (tempField[0].tagName.toLowerCase() == "input") {
                    tempFileId = tempField.val();
                } else if (tempField[0].tagName.toLowerCase() == "span") {
                    tempFileId = tempField[0].innerHTML;
                }
                var atts = upWindow.getAttBySubreference(tempFileId);
                for (var j = 0; j < atts.length; j++) {
                    attNames += atts[j].filename + ",";
                }
                if (attNames != "") {
                    attNames = attNames.substr(0, attNames.length - 1);
                }
                obj.value = attNames;
            }
            break;
        case "outwrite":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "externalwrite-ahead":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "exchangetask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "querytask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        default:
            tag = false;
    }
    if (obj.value != undefined) {
        obj.value = obj.value.replace("\r\n", ";");
        obj.value = obj.value.replace("\n", ";");
    }
    return obj;
}
function setUpFieldValue(name, value) {
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
            value);
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
            .trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {
    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var addTag = field.hasClass(addClass);
    value = trim(value);
    displayValue = trim(displayValue);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }

    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":
            if (editTag) {
                var inField = field.find("#" + fieldVal.name);
                inField.val(value);
                inField.trigger("blur");
            } else if (addTag) {
                var inField = field.find("#" + fieldVal.name);
                inField.val(value);
                inField.trigger("blur");
            }
            break;
        case "checkbox":
            if (editTag) {
                field.find("#" + fieldVal.name).attr("checked", true);
                field.find("#" + fieldVal.name).trigger("click");
            }
            break;
        case "radio":
            if (editTag) {
                field.find(":radio").eq(value).attr("checked", true);
                field.find(":radio").eq(value).trigger("click");
            }
            break;
        case "select":
            if (editTag) {
                var options = field.find("#" + fieldVal.name + " option");
                for (var k = 0; k < options.length; k++) {
                    if (options.eq(k).text() == value)
                        options.eq(k).attr("selected", true);
                }
                field.find("#" + fieldVal.name).trigger("change");
            }
            break;
        case "date":
            if (editTag) {
                field.find("#" + fieldVal.name).val(value);
                field.find("#" + fieldVal.name).trigger("blur");
            }
            break;
        case "datetime":
            if (editTag) {
                field.find("#" + fieldVal.name).val(value);
                field.find("#" + fieldVal.name).trigger("blur");
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
                alert(editTag);
                field.find("#" + fieldVal.name + "_txt").val(value);
            }
            break;
    }
}

/**
 * 去除左右空格
 */
function trim(str) {
    return (str) ? (typeof str == "string" ? str.replace(/^\s*/, "").replace(
            /\s*$/, "") : str) : "";
}

function setRaidoValue(raidoArray, value) {
    for (var i = 0; i < raidoArray.length; i++) {
        if (raidoArray[i].value == value) {
            raidoArray[i].checked = true;
        }
    }
}

function getStringLength(str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        // 单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        } else {
            len += 3;
        }
    }
    return len;
}

function checkInputLength() {
    for (var key in inputMap.inputLengthMap) {
        var length = getStringLength(document.getElementsByName(key)[0].value);
        if (length > inputMap.inputLengthMap[key]) {
            alert(inputMap.contrast[key].replace("", "") + "字符长度超过"
                    + inputMap.inputLengthMap[key]);
            return false;
        }
    }
    return true;
}

/**
 * 检查供应商名称是否符合规定,并把小写字母改成大写，把全角字符改成半角
 * 
 * @param field
 * @returns {Boolean}
 */
function checkAndReplaceProviderName(field) {
    var isRight = false;

    var charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    charlist += "abcdefghijklmnopqrstuvwxyz";
    charlist += "0123456789";
    charlist += " `~!@#$%^&*()_+-={}|[]\:\\\";'<>?,./";// 半角空格

    var providerName = field.value;
    var result = "";
    for (var i = 0; i < providerName.length; i++) {
        var c1 = providerName.charAt(i);
        var c2 = providerName.charCodeAt(i);
        if ("　" == c1) {
            result += " ";
        } else if ("，" == c1) {
            result += ",";
        } else if ("。" == c1) {
            result += ".";
        } else {
            if (charlist.indexOf(String.fromCharCode(c2 - 65248)) > -1) {
                result += String.fromCharCode(c2 - 65248);
            } else {
                result += c1;
            }
        }
    }

    field.value = trim(result.toUpperCase());
    isRight = true;

    return isRight;
}

// 已存在供应商供货范围
var providerIsExistRange = {
    // 合格供应商
    qualifiedSuppliers: null,
    potentialSuppliers: null,
    stopSuppliers: null
};

var isFillCode = function () {
    var e = getUpFieldsByFieldval("表单控件选择2");
    return e.length == 1 && getUpFieldValue(e.eq(0)).value == 'code';
};
var typeTree;
var companyTree;
var providerIsExist;
var ccontentValueArray = ["出厂价", "到库价", "FOB", "CIF", "C&F", "其他"];
var ccuspaycondValueArray = ["票后30天", "票后45天", "票后60天", "票后70天", "其他"];
var isExistInArray = function (array, value) {
    for (var i in array) {
        if (array[i] == value) {
            return i;
        }
    }
    return -1;
};

var setCcontentAndCcuspaycondDisabled = function () {
    document.getElementsByName('ccontent')[0].value = '';
    document.getElementsByName('ccuspaycond')[0].value = '';
    document.getElementById("ccontentDiv").style.display = 'none';
    document.getElementById("ccuspaycondDiv").style.display = 'none';
    document.getElementsByName("ccontentSelect")[0].selectedIndex = -1;
    document.getElementsByName("ccuspaycondSelect")[0].selectedIndex = -1;

};
var setCcontentAndCcuspaycond = function () {
    var ccontentValue = document.getElementsByName('ccontent')[0].value;
    var ccuspaycondValue = document.getElementsByName('ccuspaycond')[0].value;
    var ccontentIndex = (ccontentValue == '' ? 0 : isExistInArray(
            ccontentValueArray, ccontentValue));
    var ccuspaycondIndex = (ccuspaycondValue == '' ? 0 : isExistInArray(
            ccuspaycondValueArray, ccuspaycondValue));

    if (ccontentValue == '') {
        document.getElementsByName('ccontent')[0].value = ccontentValueArray[0];
    }

    if (ccuspaycondValue == '') {
        document.getElementsByName('ccuspaycond')[0].value = ccuspaycondValueArray[0];
    }

    if (ccontentIndex == -1) {
        ccontentIndex = 5;
        document.getElementById("ccontentDiv").style.display = '';
    } else {
        document.getElementById("ccontentDiv").style.display = 'none';
    }

    if (ccuspaycondIndex == -1) {
        ccuspaycondIndex = 4;
        document.getElementById("ccuspaycondDiv").style.display = '';
    } else {
        document.getElementById("ccuspaycondDiv").style.display = 'none';
    }
    document.getElementsByName("ccontentSelect")[0].value = ccontentIndex;
    document.getElementsByName("ccuspaycondSelect")[0].value = ccuspaycondIndex;
};

var initSupplyRangeType = function () {
    typeTree = new dhtmlXTreeObject("supplyRangeDIV", "100%", "100%", 0);
    typeTree.setSkin("csh_dhx_skyblue");
    typeTree.setImagePath("./oa2uap/js/tree/imgs/csh_dhx_skyblue/");
    typeTree.enableCheckBoxes(1);
    typeTree.enableThreeStateCheckboxes(true);
    typeTree.loadXMLString(typeXML);
    console.info(typeXML)
    if (getUpFieldsByFieldval("基建类").length === 0) {
        typeTree.deleteItem('00010010000000000LRK', false);
    } else {
        var subArray = typeTree.getSubItems("0");
        subArray = subArray.split(",");
        for (var i = 0; i < subArray.length; i++) {
            if ("00010010000000000LRK" !== subArray[i]) {
                typeTree.deleteItem(subArray[i], false);
            }
        }
    }
};
var createCompanyTree = function () {
    companyTree = new dhtmlXTreeObject("companyTreeDIV", "100%", "100%", 0);
    companyTree.setSkin("csh_dhx_skyblue");
    companyTree.setImagePath("./oa2uap/js/tree/imgs/csh_dhx_skyblue/");
    companyTree.enableCheckBoxes(1);
    companyTree.enableThreeStateCheckboxes(true);
    console.info(companyTreeXML)
    companyTree.loadXMLString(companyTreeXML);

};
var onOpinionRadioClick = function () {
    setNodeCheckWhenProviderIsExist();
};
var setNodeCheckWhenProviderIsExist = function () {
    console.log(typeJSON)
    for (var nodeID in typeJSON) {
        if (typeJSON[nodeID].isleaf == 'Y') {
            typeTree.disableCheckbox(nodeID, 0);
        }
    }
    if (document.getElementsByName("providerIsExist")[1].checked
            && getUpFieldsByFieldval("总办填写表单_").length == 0) {
        if (document.getElementsByName("opinion")[0].checked) {
            typeTree.setCheck('0', false);
            for (var nodeID in typeJSON) {
                if (typeJSON[nodeID].isleaf == 'Y') {
                    typeTree.disableCheckbox(nodeID, 0);
                }
            }
            for (var i in providerIsExistRange.qualifiedSuppliers) {
                typeTree.disableCheckbox(
                        providerIsExistRange.qualifiedSuppliers[i], 1);
            }
            for (var i in providerIsExistRange.potentialSuppliers) {
                typeTree.disableCheckbox(
                        providerIsExistRange.potentialSuppliers[i], 1);
            }
        } else if (document.getElementsByName("opinion")[1].checked) {
            typeTree.setCheck('0', false);
            for (var nodeID in typeJSON) {
                if (typeJSON[nodeID].isleaf == 'Y') {
                    typeTree.disableCheckbox(nodeID, 1);
                }
            }
            for (var i in providerIsExistRange.potentialSuppliers) {
                typeTree.disableCheckbox(
                        providerIsExistRange.potentialSuppliers[i], 0);
            }
        }
        for (var i in providerIsExistRange.stopSuppliers) {
            typeTree.disableCheckbox(providerIsExistRange.stopSuppliers[i], 1);
        }
    }
};


var initSupplyNodeChecked = function () {
    var type1Array = getUpFieldsByFieldval(inputMap.supplyRange[0][1]);
    var type2Array = getUpFieldsByFieldval(inputMap.supplyRange[1][1]);
    var type3Array = getUpFieldsByFieldval(inputMap.supplyRange[2][1]);
    for (var index = 0; index < type3Array.length; index = index + 1) {
        var rang3 = getUpFieldValue(type3Array.eq(index)).value;
        if (rang3 === "") {
            var rang2 = getUpFieldValue(type2Array.eq(index)).value;
            if (rang2 === "") {
                var rang1 = getUpFieldValue(type1Array.eq(index)).value;
                if (rang1 !== "") {
                    typeTree.setCheck(
                            getUpFieldValue(type1Array.eq(index)).value, true);
                }
            } else {
                typeTree.setCheck(getUpFieldValue(type2Array.eq(index)).value,
                        true);
            }
        } else {
            typeTree
                    .setCheck(getUpFieldValue(type3Array.eq(index)).value, true);
        }
    }
};
var initImportCompanyNodeChecked = function () {
    if (getUpFieldsByFieldval("总办填写表单_").length > 0) {
        var idArray = getUpFieldsByFieldval(inputMap.importCompany[0][1]);
        for (var index = 0; index < idArray.length; index = index + 1) {
            var idstr = getUpFieldValue(idArray.eq(index)).value;
            if (idstr !== "") {
                companyTree.setCheck(idstr, true);
            }
        }
    } else {
        // alert("公司：" + getUpAccountValue(getUpFields("单位选择器").eq(0)));
        companyTree.setCheck(getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(
                0)).id, true);
        var childNodes = companyTree.getAllSubItems('0').split(',');
        for (var i in childNodes) {
            companyTree.disableCheckbox(childNodes[i], 1);
        }
    }
};
var writeSupplyRangeToForm = function () {
    var nodes = typeTree.getAllChecked().split(",");
    console.log(nodes)
    var typeArray = [];
    // -8924145959034269856机械制造
    if (getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(0)).value != "-8924145959034269856") {
        document.getElementsByName("groupManage")[0].checked = false;
        document.getElementsByName("groupManage")[1].checked = true;
    }
    setUpFieldValue2(getUpFieldsByFieldval("是否需总裁审批").eq(0), null, null, 1);
    // getUpFields("是否需总裁审批").find(":radio").eq(0).attr("val4cal", 0);
    // getUpFields("是否需总裁审批").find(":radio").eq(1).attr("val4cal", 1);
    for (var index in nodes) {
        var nodeID = nodes[index];
        if (nodeID === "" || nodeID === null) {
            typeArray.push([["", ""], ["", ""], ["", ""]]);
        } else {
            if (getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(0)).value != "-8924145959034269856") {
                if (typeJSON[nodeID].binvgroupdot == "Y") {
                    document.getElementsByName("groupManage")[0].checked = true;
                    document.getElementsByName("groupManage")[1].checked = false;
                }
            }
            if (typeJSON[nodeID].presidentagreedto == "Y") {
                setUpFieldValue2(getUpFieldsByFieldval("是否需总裁审批").eq(0), null,
                        null, 0);
            }

            if (typeTree.hasChildren(nodeID) === 0) {
                var level = typeTree.getLevel(nodeID);
                if (level == 3) {
                    var parentID = typeTree.getParentId(nodeID);
                    typeArray.push([getTreeParentNodeArray(parentID),
                        getTreeParentNodeArray(nodeID),
                        [typeTree.getItemText(nodeID), nodeID]]);
                } else {
                    if (level == 2) {
                        typeArray.push([getTreeParentNodeArray(nodeID),
                            [typeTree.getItemText(nodeID), nodeID],
                            ["", ""]]);
                    } else {
                        if (level == 1) {
                            typeArray.push([
                                [typeTree.getItemText(nodeID), nodeID],
                                ["", ""], ["", ""]]);
                        }
                    }
                }
            }
        }
    }
    writeCheckedNodeTextToFrom(typeArray, inputMap.supplyRange);
};
var getTreeParentNodeArray = function (nodeID) {
    var parentID = typeTree.getParentId(nodeID);
    var text = typeTree.getItemText(parentID);
    return [text, parentID];
};
var writeImportCompanyNodeToForm = function () {
    if (getUpFieldsByFieldval("总办填写表单_").length > 0) {

        var nodes = companyTree.getAllChecked().split(",");
        var companyArray = [];
        for (var index in nodes) {
            var nodeID = nodes[index];
            if (nodeID === "" || nodeID === null) {
                companyArray.push([["", ""]]);
            } else {
                var level = companyTree.getLevel(nodeID);
                if (level === 1) {
                    companyArray.push([[companyTree.getItemText(nodeID),
                            nodeID]]);
                }
            }
        }
        writeCheckedNodeTextToFrom(companyArray, inputMap.importCompany);
    }
};
var writeCheckedNodeTextToFrom = function (values, repeatTableNames) {
    var valuesLength = values.length;
    addOrDelRepeat(repeatTableNames[0][0], valuesLength);
    for (var index in values) {
        var rowValues = values[index];
        for (var rowIndex in rowValues) {
            setUpFieldValue2(getUpFieldsByFieldval(
                    repeatTableNames[rowIndex][0] + "_").eq(index),
                    rowValues[rowIndex][0]);
            setUpFieldValue2(getUpFieldsByFieldval(
                    repeatTableNames[rowIndex][1]).eq(index),
                    rowValues[rowIndex][1]);
        }
    }
};
var initValue = function () {
    var contrast = inputMap.contrast;
    document.getElementsByName("providerIsExist")[1].checked = (radio1Checked = getUpFieldValue(getUpFieldsByFieldval(
            contrast["providerIsExist"]).eq(0)).value == 0);
    document.getElementsByName("providerIsExist")[0].checked = (radio0Checked = getUpFieldValue(getUpFieldsByFieldval(
            contrast["providerIsExist"]).eq(0)).value == 1);

    if (getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(0)).value == "-8924145959034269856") {
        document.getElementById("groupManageTR").style.display = "";
    }

    if (radio0Checked || radio1Checked) {
        onSupplierTypeRadioClick();
    }
    if (radio1Checked) {
        document.getElementsByName("providerCode")[0].value = getUpFieldValue(getUpFieldsByFieldval(
                contrast["providerCode"]).eq(0)).value;
    } else {
        for (var key in contrast) {
            if (key != "providerIsExist") {
                if (typeof contrast[key] == "string") {
                    if (key == 'property') {
                        document.getElementsByName(key)[0].value = (getUpFieldValue(getUpFieldsByFieldval(
                                contrast[key]).eq(0)).value == 'D' ? '0' : '1');
                    } else {
                        document.getElementsByName(key)[0].value = getUpFieldValue(getUpFieldsByFieldval(
                                contrast[key]).eq(0)).value;
                    }
                } else {
                    if (typeof contrast[key] == "object") {
                        if (document.getElementsByName(key)[0].tagName
                                .toUpperCase() == "SELECT") {
                            document.getElementsByName(key)[0].value = getUpFieldValue(getUpFieldsByFieldval(
                                    contrast[key][1]).eq(0)).value;
                        } else {
                            if (key == "opinion" || key == "groupManage") {
                                document.getElementsByName(key)[0].checked = (getUpFieldValue(getUpFieldsByFieldval(
                                        contrast[key][1]).eq(0)).value == 0)
                                document.getElementsByName(key)[1].checked = (getUpFieldValue(getUpFieldsByFieldval(
                                        contrast[key][1]).eq(0)).value == 1);
                            }
                        }
                    }
                }
            }
        }
        initSupplyNodeChecked();
        initImportCompanyNodeChecked();
    }
    setCcontentAndCcuspaycond();
};
var getTRParentNode = function (node) {
    var tempNode = node;
    while (true) {
        if (tempNode && tempNode.tagName.toUpperCase() != "TR") {
            tempNode = tempNode.parentNode;
        } else {
            break;
        }
    }
    return tempNode.parentNode;
};
window.onload = function () {
    var sign = false;
    if (isFillCode()) {
        if (operator == 1) {
            sign = true;
            document
                    .write('<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body style="margin-top: 50px; font-family: 微软雅黑; font-size: 10.5pt;"><table align="center" style="width: 280px"><tr><td width="130px" >供应商编码:</td><td><input id="code" type="text" width="100%" onkeydown="onEnterKeyPress()" style="font-family: font-family :   Arial; font-size: 10.5pt; color: #333399;; font-size: 10.5pt;"></td></tr><tr><td width="100px"></td><td align="right"><input id="button" type="button" value="确定" onclick="onButtonClick()" style="FONT-SIZE: 8pt; WIDTH: 60px; FONT-FAMILY: 微软雅黑"></td></tr></table></body><script src="./oa2uap/js/checkPrivoiderCode.js"></script></html>');
        }
    } else {
        if (typeXML == "") {
            alert("未读取到供货范围，请联系ＯＡ系统管理员");
        }
        initSupplyRangeType();
        createCompanyTree();
        initValue();
    }

    if (!sign) {
        if (typeTree) {
            for (var nodeID in typeJSON) {
                if (typeJSON[nodeID].isleaf != 'Y') {
                    typeTree.disableCheckbox(nodeID, 1);
                }
            }
        }
        if (getUpFields("总办填写表单_").length == 0) {
            companyTree
                    .setCheck(
                            getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(0)).id,
                            true);
            var childNodes = companyTree.getAllSubItems('0').split(',');
            for (var i in childNodes) {
                companyTree.disableCheckbox(childNodes[i], 1);
            }
        }
    }
    if (document.getElementsByName("cVenBankMemo")
            && document.getElementsByName("cVenBankMemo")[0])
        document.getElementsByName("cVenBankMemo")[0].maxLength = 40;
    // if (!isFillCode())
    // initAptitude();
};

var providerNameIsExist = function () {

};

function onButtonClick() {
    var providerName = document.getElementsByName("providerName")[0].value;

    if (!providerName || providerName == "") {
        alert("供应商名称不能为空");
        return {
            dataValue: "unfinished"
        };
    }

    if (!checkAndReplaceProviderName(document.getElementsByName("providerName")[0])) {
        return {
            dataValue: "unfinished"
        };
    }
    providerName = document.getElementsByName("providerName")[0].value;

    if (!checkInputLength()) {
        return {
            dataValue: "unfinished"
        };
    }

    var isExist = document.getElementsByName("providerIsExist")[1].checked;
    var param = ("&isExist=" + isExist + "&writer=" + (getUpFieldsByFieldval("总办填写表单_").length > 0 ? 1
            : 2));
    if (getUpFields("总办填写表单_").length > 0 && isExist) {
        var typeNodes = typeTree.getAllChecked();
        var companyNodes = companyTree.getAllChecked();
        var code = document.getElementsByName("query_providerCode")[0].value;
        param += ("&typeNodes=" + typeNodes + "&companyNodes=" + companyNodes
                + "&code=" + code);
    }

    createAjax(
            "method=checkProviderNameIsExist&providerName="
            + (encodeURIComponent(providerName)) + param,
            "./oa2uapController.do",
            function (xmlhttp, hideLodingDiv) {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    hideLodingDiv();
                    text = xmlhttp.responseText;
                    var result = eval('(' + text + ')');
                    if (result.success == 'false') {
                        alert("数据库访问异常，无法验证用户名是否已存在");
                    } else if ((!result.code || result.code == '' || result.code == document
                            .getElementsByName("providerCode")[0].value)) {
                        if (getUpFields("总办填写表单_").length > 0 && isExist) {
                            if (result.msg) {

                                var companyNodeIDArray = companyTree
                                        .getAllChecked().split(',');
                                var typeIDArray = typeTree.getAllChecked()
                                        .split(',');
                                var message = '';
                                var sign = false;
                                if (document.getElementsByName("opinion")[1].checked) {
                                    for (var cIndex in companyNodeIDArray) {
                                        for (var tIndex in typeIDArray) {
                                            if (typeIDArray[tIndex]
                                                    && typeIDArray[tIndex] != ''
                                                    && typeJSON[typeIDArray[tIndex]].isleaf == 'Y') {
                                                for (var mIndex in result.msg) {
                                                    if (result.msg[mIndex].pk_corp == companyNodeIDArray[cIndex]
                                                            && result.msg[mIndex].pk_invclass == typeIDArray[tIndex]) {
                                                        if (result.msg[mIndex].cvendorclass == 2) {
                                                            sign = true;
                                                        }
                                                    }
                                                }
                                                if (!sign) {
                                                    message += '\n';
                                                    message += companyTree
                                                            .getItemText(companyNodeIDArray[cIndex]);
                                                    message += "      ";
                                                    message += typeTree
                                                            .getItemText(typeIDArray[tIndex]);
                                                }
                                                sign = false;
                                            }
                                        }
                                    }
                                    if (message != '') {
                                        message = "以下供货范围不是潜在的，不会导入供应商系统："
                                                + message;
                                    }
                                } else {

                                    for (var cIndex in companyNodeIDArray) {
                                        for (var tIndex in typeIDArray) {
                                            if (typeIDArray[tIndex]
                                                    && typeIDArray[tIndex] != ''
                                                    && typeJSON[typeIDArray[tIndex]].isleaf == 'Y') {
                                                for (var mIndex in result.msg) {
                                                    if (result.msg[mIndex].pk_corp == companyNodeIDArray[cIndex]
                                                            && result.msg[mIndex].pk_invclass == typeIDArray[tIndex]
                                                            && result.msg[mIndex].cvendorclass != '1'
                                                            && result.msg[mIndex].cvendorclass != '2'
                                                            && result.msg[mIndex].cvendorclass != '3') {
                                                        sign = true;
                                                    }
                                                }
                                                if (sign) {
                                                    message += '\n';
                                                    message += companyTree
                                                            .getItemText(companyNodeIDArray[cIndex]);
                                                    message += "      ";
                                                    message += typeTree
                                                            .getItemText(typeIDArray[tIndex]);
                                                }
                                                sign = false;
                                            }
                                        }
                                    }
                                    if (message != '') {
                                        message = "以下供货范围已经是潜在/合格的，或者已被列入黑名单，不会导入供应商系统："
                                                + message;
                                    }
                                }
                                if (message != '') {
                                    alert(message);
                                }
                            } else {
                                alert("验证导入的供货范围失败");
                            }
                        }
                        // opinion:["处理意见", "处理意见值"],
                        // groupManage:["集团管控", "是否集团重点管控"],
                        var contrast = inputMap.contrast;
                        // up_doc.getElementById(contrast["providerCode"]).is_null
                        // = "true";
                        // up_doc.getElementById(contrast["providerCode"]).fireEvent('onchange');
                        writeSupplyRangeToForm();
                        writeImportCompanyNodeToForm();
                        for (var key in contrast) {
                            var node = document.getElementsByName(key)[0];
                            var node2 = document.getElementsByName(key)[1];
                            if (node.tagName.toUpperCase() == "SELECT"
                                    && key != "cvenfygl" && key != "qylb") {
                                if (node.selectedIndex != -1) {
                                    if (typeof contrast[key] == 'string') {
                                        setUpFieldValue2(
                                                getUpFieldsByFieldval(
                                                        contrast[key] + "_")
                                                .eq(0),
                                                node.options[node.selectedIndex].text);
                                    } else {
                                        setUpFieldValue2(getUpFieldsByFieldval(
                                                contrast[key][1]).eq(0),
                                                node.value);
                                        setUpFieldValue2(
                                                getUpFieldsByFieldval(
                                                        contrast[key][0] + "_")
                                                .eq(0),
                                                node.options[node.selectedIndex].text);
                                    }
                                } else {
                                    if (typeof contrast[key] == 'string') {
                                        setUpFieldValue2(getUpFieldsByFieldval(
                                                contrast[key]).eq(0), "");
                                    } else {
                                        setUpFieldValue2(getUpFieldsByFieldval(
                                                contrast[key][1]).eq(0), "");
                                        setUpFieldValue2(getUpFieldsByFieldval(
                                                contrast[key][0] + "_").eq(0),
                                                "");
                                    }
                                }
                            } else {
                                if (node.type.toUpperCase() == "RADIO") {
                                    if (key == "opinion") {
                                        setUpFieldValue2(getUpFieldsByFieldval(
                                                contrast[key][0] + "_").eq(0),
                                                node.checked ? "导入潜在供应商名录"
                                                : node2.checked ? "导入合格供应商名录" : "导入研发供应阶段");
                                        setUpFieldValue2(getUpFieldsByFieldval(
                                                contrast[key][1]).eq(0),
                                            node.checked ? 0
                                                : node2.checked ? 1 : 2);

                                    } else {
                                        if (key == "groupManage") {
                                            setUpFieldValue2(
                                                    getUpFieldsByFieldval(
                                                            contrast[key][0]
                                                            + "_")
                                                    .eq(0),
                                                    node.checked ? "在集团重点管控物料类别清单内"
                                                    : "不在集团重点管控类别清单内");
                                            setUpFieldValue2(
                                                    getUpFieldsByFieldval(
                                                            contrast[key][1])
                                                    .eq(0),
                                                    node.checked ? 0 : 1);
                                        } else {
                                            if (key == "providerIsExist") {
                                                setUpFieldValue2(
                                                        getUpFieldsByFieldval(
                                                                contrast[key])
                                                        .eq(0),
                                                        document
                                                        .getElementsByName(key)[1].checked ? 0
                                                        : 1);
                                                // up_doc
                                                // .getElementsByName(contrast[key])[0].checked
                                                // = document
                                                // .getElementsByName(key)[1].checked;
                                                // up_doc
                                                // .getElementsByName(contrast[key])[up_doc
                                                // .getElementsByName(contrast[key]).length
                                                // - 1].checked = node.checked;
                                            }
                                        }
                                    }
                                } else {
                                    setUpFieldValue2(getUpFieldsByFieldval(
                                            contrast[key] + "_").eq(0),
                                            node.value);
                                }
                            }
                        }

                        writeSuccess = true;
                        fy_dialog_close();
                    } else {
                        alert("供应商名称已存在，此供应商编码为：" + result.code);
                    }
                }
            });
    // return {
    // dataValue : "unfinished"
    // };
}
;
var onSupplierTypeRadioClick = function () {
    var value = document.getElementsByName("providerIsExist")[1].checked;
    // 判断是否变更
    if (providerIsExist == null || providerIsExist != value) {
        providerIsExist = value;
        // resetAptitude();
        if (providerIsExist) {
            setInputDisabled(inputMap.providerIsNotExist.handwritingInput);
            setInputReadonly(inputMap.providerIsExist.firstStep.redonly);
            setInputCanFill(inputMap.providerIsExist.firstStep.fill);
            document.getElementById("supplyRangeParentDIV").style.display = "none";
            document.getElementById("companyTreeParentDIV").style.display = "none";
            document.getElementById("queryTR").style.display = "";
            typeTree.setCheck(0, false);
            companyTree.setCheck(0, false);

            if (getUpFields("总办填写表单_").length > 0) {
                document.getElementsByName("opinion")[0].checked = true;
                document.getElementsByName("opinion")[1].disabled = true;
            }

            setCcontentAndCcuspaycondDisabled();
        } else {
            setInputDisabled(inputMap.providerIsExist.firstStep.fill);
            setInputDisabled(inputMap.providerIsExist.firstStep.redonly);
            document.getElementById("supplyRangeParentDIV").style.display = "";
            document.getElementById("companyTreeParentDIV").style.display = "";
            document.getElementById("queryTR").style.display = "none";
            setInputCanFill(inputMap.providerIsNotExist.handwritingInput);
            document.getElementsByName("groupManage")[0].checked = true;

            document.getElementsByName("opinion")[0].checked = true;
            document.getElementsByName("opinion")[1].disabled = true;

            setCcontentAndCcuspaycondDisabled();

            // showAptitude();
        }
    }
};

var createAjax = function (params, url, operator) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
        // Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        operator(xmlhttp, function () {
            // window.parent.document.getElementById("lodingDiv").style.display
            // = 'none';
        });
    };
    // window.parent.document.getElementById("lodingDiv").style.height =
    // window.parent.document.body.clientHeight
    // + 5 + "px";
    // window.parent.document.getElementById("lodingDiv").style.display = '';
    xmlhttp.open("get", url + "?" + params + "&temp=" + Math.random(), true);
    xmlhttp.send();
};

var queryProviderInfo = function () {
    try {
        var value = document.getElementById("query_providerCode").value;
        value = value.replace(/ /g, '');
        document.getElementById("query_providerCode").value = value;
        if (value !== null && value !== "") {
            createAjax(
                    ("method=findProviderInfo&providerCode=" + value),
                    "./oa2uapController.do",
                    function (xmlhttp, hideLodingDiv) {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            text = xmlhttp.responseText;
                            if (text == 1) {
                                alert("用户已经掉线，请先登录");
                            } else if (text == 2) {
                                alert("供应商编码不能为空");
                            } else if (text == 3) {
                                alert("供应商编码输入错误，无此供应商或已被停用");
                            } else {
                                var obj = eval('(' + text + ')');
                                document.getElementById("supplyRangeParentDIV").style.display = "";
                                document.getElementById("companyTreeParentDIV").style.display = "";
                                setInputCanFill(inputMap.providerIsNotExist.handwritingInput);
                                document.getElementsByName("opinion")[0].checked = true;
                                document.getElementsByName("groupManage")[0].checked = true;
                                for (var key in obj) {
                                    var dom = document.getElementsByName(key)[0];
                                    if (typeof dom === 'object') {
                                        if (key == 'property') {
                                            dom.value = (obj[key] == 'D' ? '0'
                                                    : '1');
                                        } else {
                                            dom.value = obj[key];
                                        }
                                    }
                                }
                                document.getElementsByName("providerCode")[0].value = value;

                                setCcontentAndCcuspaycond();

                                // 合格供应商
                                providerIsExistRange.qualifiedSuppliers = obj.qualifiedSuppliers;
                                providerIsExistRange.potentialSuppliers = obj.potentialSuppliers;
                                providerIsExistRange.stopSuppliers = obj.stopSuppliers;
                                setNodeCheckWhenProviderIsExist();
                                // showAptitude();
                            }
                            hideLodingDiv();
                        }
                    });
        } else {
            alert("供应商编码不能为空.");
        }
    } catch (e) {
        alert("错误" + e);
    }
};
var setInputCanFill = function (nameArray) {
    for (var index in nameArray) {
        var inputs = document.getElementsByName(nameArray[index]);
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type.toUpperCase() == "RADIO") {
                inputs[i].checked = false;
            } else {
                inputs[i].value = "";
                inputs[i].className = "manualInput";
            }
            inputs[i].readonly = false;
            inputs[i].disabled = false;
        }
    }
};
var setInputDisabled = function (nameArray) {
    for (var index in nameArray) {
        var inputs = document.getElementsByName(nameArray[index]);
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type.toUpperCase() == "RADIO") {
                inputs[i].checked = false;
            } else {
                inputs[i].value = "";
                inputs[i].className = "disabledInput";
            }
            inputs[i].disabled = true;
        }
    }
};
var setInputReadonly = function (nameArray) {
    for (var index in nameArray) {
        var inputs = document.getElementsByName(nameArray[index]);
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type.toUpperCase() == "RADIO") {
                inputs[i][0].checked = false;
            } else {
                inputs[i].value = "";
                inputs[i].className = "readOnlyInput";
            }
            inputs[i].disabled = false;
            inputs[i].readOnly = "readonly";
        }
    }
};

var clearAllInput = function () {
    // setInputDisabled(inputMap.contrast);
};
var onCcontentSelectChange = function (node) {
    if (node.value == 5) {
        document.getElementById("ccontentDiv").style.display = '';
        document.getElementsByName('ccontent')[0].value = '';
    } else {
        document.getElementById("ccontentDiv").style.display = 'none';
        document.getElementsByName('ccontent')[0].value = ccontentValueArray[node.value];
    }
};
var onCcuspaycondSelectChange = function (node) {
    if (node.value == 4) {
        document.getElementById("ccuspaycondDiv").style.display = '';
        document.getElementsByName('ccuspaycond')[0].value = '';
    } else {
        document.getElementById("ccuspaycondDiv").style.display = 'none';
        document.getElementsByName('ccuspaycond')[0].value = ccuspaycondValueArray[node.value];
    }
};
var inputMap = {
    providerIsExist: {
        firstStep: {
            redonly: ["providerCode"],
            fill: ["query_providerCode"]
        },
        readonlyInput: [],
        disabledInput: []
    },
    supplyRange: [["供货范围分类1", "供货范围分类1值"], ["供货范围分类2", "供货范围分类2值"],
        ["供货范围分类3", "供货范围分类3值"]],
    importCompany: [["导入制造部名称", "导入制造部值"]],
    providerIsNotExist: {
        handwritingInput: ["providerName", "opinion", "groupManage",
            "reason", "similarSuppliers", "address", "linkman",
            "supplyCycle", "cvenbank", "supplyAddress", "tel",
            "cpurbillcode", "bankAccount", "taxRegister", "fax",
            "couttype", "cmoneytype", "qualitySystem", "postCode",
            "companyType", "ccuspaycond", "property", "email", "ccontent",
            "fax", 'ccuspaycondSelect', 'ccontentSelect', 'cVenBankMemo',
            'bankAccountName', 'bankCode', "cvenfygl", 'qylb', 'zczj',
            'clsj', 'zgrs', 'jycs', 'frdb', 'frdbsfz', 'nxse']
    },
    contrast: {
        providerName: "供应商名称",
        providerCode: "供应商编码",
        opinion: ["处理意见", "处理意见值"],
        groupManage: ["集团管控", "是否集团重点管控"],
        reason: "新增原因",
        similarSuppliers: "同类供应商",
        address: "企业地址",
        linkman: "联系人",
        supplyCycle: "供货周期",
        cvenbank: "结算银行",
        supplyAddress: "发货地址",
        tel: "电话号码",
        cpurbillcode: "发票税码",
        bankAccount: "银行账号",
        taxRegister: "税务登记号",
        fax: "传真号码",
        couttype: ["物流方式", "物流方式PK"],
        cmoneytype: ["币种", "币种PK"],
        qualitySystem: "质量体系",
        postCode: "邮编",
        companyType: ["企业类型", "企业类型PK"],
        ccuspaycond: "付款条件",
        property: "属性",
        email: "电子邮箱",
        ccontent: "价格条款",
        fax : "传真号码",
                providerIsExist: "是否在供应商名录内",
        cVenBankMemo: "开户银行",
        bankAccountName: '银行开户名',
        bankCode: '银行代码',
        cvenfygl: "是否福耀关联方"
                /*
                 * , qylb : '企业类别', zczj : '注册资金', clsj : '成立时间', zgrs : '职工总人数', jycs :
                 * '经营场所', frdb : '法人代表', frdbsfz : '法人代表身份证', nxse : '年销售额'
                 */
    },
    inputLengthMap: {
        providerName: 100,
        providerCode: 20,
        address: 100,
        linkman: 20,
        supplyCycle: 20,
        cvenbank: 100,
        supplyAddress: 100,
        tel: 20,
        cpurbillcode: 20,
        bankAccount: 45,
        taxRegister: 20,
        fax: 20,
        qualitySystem: 20,
        postCode: 20,
        ccuspaycond: 100,
        property: 5,
        email: 100,
        ccontent: 100,
        fax : 20,
                cVenBankMemo: 100,
        bankAccountName: 96,
        bankCode: 20
    }
};